﻿using Autofac.Extras.DynamicProxy;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Truron.Purchase.Interface;
using Truron.Purchase.Model;
using Truron.Purchase.Model.RemoteModel;
using Truron.Purchase.Service.DbContext;
using Truron.Purchase.Utility;
using Truron.Purchase.Utility.RedisHelper;

namespace Truron.Purchase.Service
{
    [Intercept(typeof(CustomAutofacAop))]
    public class Purchase_OuterRequestDetailService: IPurchase_OuterRequestDetailService
    {
        private List<Purchase_OuterRequestDetail> Init(bool isInit = false)
        {
            try
            {
                if (isInit)//初始化
                    RedisBase.Hash_Remove(StaticConstraint.PurchaseOuterRequestDetailCacheKey);
                var List = RedisBase.Hash_GetAll<Purchase_OuterRequestDetail>(StaticConstraint.PurchaseOuterRequestDetailCacheKey);
                if (List != null && List.Count > 0)
                    return List;
                string sql = string.Format(@" select a.* from Purchase_OuterRequestDetail a where a.Status!={0} ", (int)Status.delete);
                List = DapperDbContext.Query<Purchase_OuterRequestDetail>(sql).ToList();
                if (List.Count > 0)
                {
                    foreach (var item in List)
                        RedisBase.Hash_Set(StaticConstraint.PurchaseOuterRequestDetailCacheKey, item.Id, item);
                    RedisBase.Item_SetExpire(StaticConstraint.PurchaseOuterRequestDetailCacheKey, DateTime.Now.AddDays(7));
                }
                return List;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"初始化单据数据失败,isInit:{isInit},详细:{ex.ToString()}");
            }
            return new List<Purchase_OuterRequestDetail>();
        }
        public int save(Purchase_OuterRequestDetail ent, UserCache user)
        {
            IDbModelService<Purchase_OuterRequestDetail> db = new DbModelService<Purchase_OuterRequestDetail>();
            IDbTransaction transaction = null;
            try
            {
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    transaction = conn.BeginTransaction();
                    if (ent.Id == 0)
                    {
                        ent.Create(user);
                        var noteid = db.InsertOne(ent, conn, transaction);
                        ent.Id = noteid;

                        //RedisBase.Hash_Remove(StaticConstraint.PurchaseOuterRequestDetailCacheKey);
                        RedisBase.Hash_Set(StaticConstraint.PurchaseOuterRequestDetailCacheKey, ent.Id, ent);
                        transaction.Commit();
                        return noteid;
                    }
                    else
                    {
                        ent.Modify(user);
                        db.UpdateById(ent, conn, transaction);
                        transaction.Commit();
                        if (ent != null)//更新线索缓存
                        {

                            RedisBase.Hash_Remove(StaticConstraint.PurchaseOuterRequestDetailCacheKey, ent.Id.ToString());
                            RedisBase.Hash_Set(StaticConstraint.PurchaseOuterRequestDetailCacheKey, ent.Id, ent);
                        }
                        return ent.Id;
                    }

                }
            }
            catch (Exception ex)
            {

                transaction.Rollback();
                return -1;
            }
        }
        public List<Purchase_OuterRequestDetail> GetDetailList(int RequestId)
        {
            return Init().FindAll(x => x.RequestId == RequestId).OrderBy(x => x.Id).ToList();
        }
        public (int count, List<Purchase_OuterRequestDetail> list) GetList(string searchKey, int pageSize, int pageIndex, string searchJson,List<int> FinishIds, List<int> ownerIds,int OuterStatus)
        {
            var queryParam = searchJson.ToJObject();
            int pageNum = (pageIndex - 1) * pageSize;
            var List = Init().Where(x=>(ownerIds.Contains(x.OwnerId)||x.OwnerId==0)&&x.OuterStatus>=0).OrderByDescending(x => x.CreateTime).ToList();
            if(!searchKey.IsEmpty())
            {
                List = List.FindAll(x => (x.DetailNo.Contains(searchKey)|| x.OrderNo.Contains(searchKey)));
            }
            if (!queryParam["beginTime"].IsEmpty())
            {
                List = List.FindAll(x => x.CreateTime >= Convert.ToDateTime(queryParam["beginTime"]));
            }
            if (!queryParam["endTime"].IsEmpty())
            {
                List = List.FindAll(x => x.CreateTime <= Convert.ToDateTime(queryParam["endTime"]));
            }
            if (!queryParam["type"].IsEmpty())
            {
                if (queryParam["type"].ToString() == "user")
                {
                    List = List.FindAll(x => x.OwnerId == (int)queryParam["value"]);
                }
                else if(queryParam["type"].ToString() == "private")
                {
                    List = List.FindAll(x => x.OwnerId !=0 );
                }
                else if (queryParam["type"].ToString() == "public")
                {
                    List = List.FindAll(x => x.OwnerId == 0);
                }
                else if (queryParam["type"].ToString() == "status")
                {
                    List = List.FindAll(x => x.OuterStatus == (int)queryParam["value"]);
                }
                else if (queryParam["type"].ToString() == "statususer")
                {
                    string[] arr = queryParam["value"].ToString().Split("-");
                    List = List.FindAll(x => x.OuterStatus == Convert.ToInt32(arr[0]) && x.OwnerId == Convert.ToInt32(arr[1]));
                }
                else if (queryParam["type"].ToString() == "userstatus")
                {
                    string[] arr = queryParam["value"].ToString().Split("-");
                    List = List.FindAll(x => x.OuterStatus == Convert.ToInt32(arr[1]) && x.OwnerId == Convert.ToInt32(arr[0]));
                }
            }
            if (OuterStatus!=-1)
            {
                List = List.FindAll(x => x.OuterStatus == OuterStatus);
            }
            var ParamList = List.OrderBy(x => x.CreateTime).Skip(pageNum).Take(pageSize).ToList();
            return (ParamList.Count, ParamList);
        }
        public void UpdateOwner(int UserId, List<int> RequestIds,UserCache userinfo)
        {
            IDbModelService<Purchase_OuterRequestDetail> db = new DbModelService<Purchase_OuterRequestDetail>();
            IDbTransaction transaction = null;

                
            using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
            {
                transaction = conn.BeginTransaction();
                List<Purchase_OuterRequestDetail> list = Init().Where(x => RequestIds.Contains(x.Id)).ToList();
                try
                {
                    foreach (var entity in list)
                    {

                        entity.Modify(userinfo);
                        entity.OuterStatus = (int)OuterRequestUnitStatus.deal;
                        entity.OwnerId = UserId;
                        db.UpdateById(entity, conn, transaction);
                        
                    }
                    transaction.Commit();
                    foreach(var entity in list)
                    {
                        RedisBase.Hash_Remove(StaticConstraint.PurchaseOuterRequestDetailCacheKey, entity.Id.ToString());
                        RedisBase.Hash_Set(StaticConstraint.PurchaseOuterRequestDetailCacheKey, entity.Id, entity);
                    }
                }
                catch(Exception ex)
                {
                    transaction.Rollback();
                }
            }
            
           
        }
        public void UpdateStatus(int RequestId, int Status, UserCache user)
        {
            Purchase_OuterRequestDetail entity = Init().Find(x => x.Id == RequestId);
            //entity.Modify(user);
            entity.OuterStatus = Status;
            save(entity, user);
        }
        public List<Purchase_OuterRequestDetail> GetRelationRequestList(List<int> RequestIds)
        {
            return Init().Where(x => RequestIds.Contains(x.Id)).ToList();
        }
        public List<Purchase_OuterRequestDetail> GetAllList()
        {
            return Init().ToList();
        }
        //public List<int> GetRequestIds(List<int> RequestDIds)
        //{
        //    return Init().Where(x=>RequestDIds.Contains(x.))
        //}
        public (int count, List<Purchase_OuterRequestDetail> list) GetAuditList(string searchKey, int pageSize, int pageIndex, string searchJson, List<int> userIds)
        {
            var queryParam = searchJson.ToJObject();
            int pageNum = (pageIndex - 1) * pageSize;
            var List = Init().Where(x => (userIds.Contains(x.CreateUser))).OrderByDescending(x => x.CreateTime).ToList();
            if (!searchKey.IsEmpty())
            {
                List = List.FindAll(x => (x.DetailNo.Contains(searchKey) || x.OrderNo.Contains(searchKey)));
            }
            if (!queryParam["type"].IsEmpty())
            {
                if (queryParam["type"].ToString() == "user")
                {
                    List = List.FindAll(x => x.CreateUser == (int)queryParam["value"]);
                }
                else if (queryParam["type"].ToString() == "status")
                {
                    List = List.FindAll(x => x.OuterStatus == (int)queryParam["value"]);
                }
                else if (queryParam["type"].ToString() == "statususer")
                {
                    string[] arr = queryParam["value"].ToString().Split(",");
                    List = List.FindAll(x => x.OuterStatus == Convert.ToInt32(arr[0]) && x.CreateUser == Convert.ToInt32(arr[1]));
                }
                else if (queryParam["type"].ToString() == "userstatus")
                {
                    string[] arr = queryParam["value"].ToString().Split(",");
                    List = List.FindAll(x => x.OuterStatus == Convert.ToInt32(arr[1]) && x.CreateUser == Convert.ToInt32(arr[0]));
                }
            }
            var PageList = List.OrderBy(x => x.CreateTime).Skip(pageNum).Take(pageSize).ToList();
            return (PageList.Count, PageList);
        }
        public Purchase_OuterRequestDetail GetEntity(int id)
        {
            return Init().Find(x => x.Id == id);
        }
    }
}
